const int DQ=2;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  convertTemp();
  delay(1000);
  float tempVal=readTemp();
  Serial.print("read temp:");
  Serial.println(tempVal);
  delay(5000);
}

void convertTemp(){
  int isInited=initDs18b20();
  if(isInited){
    sendDs18b20Commd(0xcc);
    sendDs18b20Commd(0x44);
  }else{
    Serial.print("no ds18b20 reponse!");
  }
}

float readTemp(){
  bool isInited=initDs18b20();
  float res=0;
  int tempVal=0;
  bool isNegative;
  if(isInited){
    sendDs18b20Commd(0xcc);
    sendDs18b20Commd(0xbe);
    uint8_t LSB=readDs18b20();
    uint8_t HSB=readDs18b20();
    isNegative=HSB>>7;
    tempVal = LSB|(HSB&0x07)<<8;
  }else{
    Serial.print("no ds18b20 reponse!");
    return 0.0;
  }
  res=tempVal*0.0625;
  if(isNegative){
    return -res;
  }else{
    return res;
  }
}

bool initDs18b20(){
  pinMode(DQ,OUTPUT);
  digitalWrite(DQ,LOW);
  delayMicroseconds(500);
  pinMode(DQ,INPUT);
  delayMicroseconds(16);
  int index=0;
  bool res=0;
  while(index<=480){
    if(!digitalRead(DQ)){
      res=1;
    }
    delayMicroseconds(1);
    index++;
  }
  return res;
}

void sendDs18b20Commd(char comm){
  pinMode(DQ,OUTPUT);
  for(int i=0;i<8;i++){
    int bit=comm&0x01;
    digitalWrite(DQ,LOW);
    delayMicroseconds(15);
    if(bit==1){
      digitalWrite(DQ,HIGH);
    }
    delayMicroseconds(45);
    digitalWrite(DQ,HIGH);
    delayMicroseconds(2);
    comm=comm>>1;
  }
}

uint8_t readDs18b20(){
  uint8_t returnVal;
  pinMode(DQ,OUTPUT);
  for(uint8_t i=0;i<8;i++){
    pinMode(DQ,OUTPUT);
    digitalWrite(DQ,LOW);
    delayMicroseconds(5);
    pinMode(DQ,INPUT);
    delayMicroseconds(15);
    uint8_t index=0;
    uint8_t bit=1;
    while(index<50){
      if(!digitalRead(DQ)){
        bit=0;
      }
      delayMicroseconds(1);  
      index++;
    }
    if(bit==1){
      returnVal=returnVal|0x80;
    }
    if(i!=7){
      returnVal=returnVal>>1;
    }
  }
  return returnVal;
}
